package org.moda.sql.parser;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import org.moda.common.Either;
import org.moda.sql.visitor.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: SqlParser
 * @Description:
 * @Author: xuanyang
 * @Date: 2024-11-24 15:26
 * @Version: 1.0
 **/
public class SqlParser {
    public static Either<Throwable, SqlStructure> parse(String sql) {
        try {
            Statement parse = CCJSqlParserUtil.parse(sql);
            if (parse instanceof Select select) {
                PlainSelect plainSelect = select.getPlainSelect();

                // 3. 获取表名
                String tableName = TableVisitor.tableName(plainSelect.getFromItem());

                // 2. 获取select的字段
                List<SelectItemInfo> selectItems = plainSelect.getSelectItems().stream()
                    .map(SelectItemVisitor::selectItem)
                    .toList();

                // 3. 获取where条件
                Expression where = plainSelect.getWhere();
                Condition condition = ExpressionVisitor.parse(where);

                return Either.right(new SqlStructure(selectItems, tableName, condition));
            }

            return Either.left(new RuntimeException("sql parse error"));
        } catch (Exception e) {
            return Either.left(e);
        }
    }
}
